//
//  InfinitelyScrollingView.m
//  TRoad2
//
//  Created by ZhangYanhua on 14/11/13.
//  Copyright (c) 2014年 Mach. All rights reserved.
//

#import "LeftInfinitelyScrollingView.h"

#define CELL_COUNT_MULTIPER        1

@interface LeftInfinitelyScrollingView()

@property (nonatomic, strong) NSTimer *scrollTimer;

@end

@implementation LeftInfinitelyScrollingView

- (void)scrollToNextPage:(NSTimer *)timer
{
    if (!self.collectionView.isDragging && !self.collectionView.isTracking) {
        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:CGPointMake(self.collectionView.contentOffset.x + self.collectionView.frame.size.width / 2.0f, 1.0f)];
        
        if (indexPath == nil) {
            NSArray *array = [self.collectionView indexPathsForVisibleItems];
            indexPath = [array firstObject];
        }

        if (indexPath) {
            NSInteger index = (indexPath.row + 1);
            NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:index inSection:0];

            [self.collectionView scrollToItemAtIndexPath:newIndexPath
                                        atScrollPosition:UICollectionViewScrollPositionLeft
                                                animated:YES];
        }
    }
}

-(void)setupDataForCollectionView {
    // Create the original set of data
    self.collectionView.scrollEnabled = ([self.itemArray count] > 1);
    
    [self.collectionView reloadData];

    if (self.itemArray.count > 1) {
        NSInteger centerIndex = 0;//(CELL_COUNT_MULTIPER / 2 * numberOfItem);

        NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:centerIndex inSection:0];

        [self.collectionView scrollToItemAtIndexPath:newIndexPath
                                    atScrollPosition:UICollectionViewScrollPositionLeft
                                            animated:NO];
        
        [_scrollTimer invalidate];
        _scrollTimer = nil;

        // 商品不需要自动滚动
//        CGFloat delayInSeconds = 0.5 * (_currentIndex % 5);
//        __weak LeftInfinitelyScrollingView *weakSelf = self;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [weakSelf startTimer];
//        });
    } else {
        [_scrollTimer invalidate];
        _scrollTimer = nil;
    }
}

- (void)startTimer
{
    if (_scrollTimer) {
        return;
    }

    _scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f
                                                    target:self
                                                  selector:@selector(scrollToNextPage:)
                                                  userInfo:nil
                                                   repeats:YES];
}

- (void)dealloc
{
}

- (id)initWithFrame:(CGRect)aFrame ItemArray:(NSArray *)itemArray
{
    if (self = [super initWithFrame:aFrame]) {
        _itemArray = itemArray;
        
        [self commonSetup];
        [self setupDataForCollectionView];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        _itemArray = nil;
        
        [self commonSetup];
        [self setupDataForCollectionView];
    }
    
    return self;
}

- (void)setItemArray:(NSArray *)itemArray
{
    if (![_itemArray isEqual:itemArray]) {
        _itemArray = itemArray;
        
        [self setupDataForCollectionView];
    }
}

- (void)commonSetup
{
    self.collectionViewLayout = [[LeftPagingFlowCollectionLayout alloc] init];
    [self.collectionViewLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [self.collectionViewLayout setMinimumInteritemSpacing:5.0f];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds
                                             collectionViewLayout:self.collectionViewLayout];
    [self.collectionView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    [self.collectionView setDataSource:self];
    [self.collectionView setDelegate:self];
    [self.collectionView setShowsHorizontalScrollIndicator:NO];
    [self.collectionView setShowsVerticalScrollIndicator:NO];
    [self.collectionView setBackgroundColor:[UIColor whiteColor]];
    
    [self.collectionView setBounces:NO];

    [self addSubview:self.collectionView];
}

#pragma mark - UICollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    if ([self.itemArray count] <= 1) {
        return self.itemArray.count;
    }

    return CELL_COUNT_MULTIPER * self.itemArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.delegate respondsToSelector:@selector(collectionView:cellForItemAtIndexPath:withItem:)]) {
        return [self.delegate collectionView:cv
                      cellForItemAtIndexPath:indexPath
                                    withItem:self.itemArray[indexPath.row % self.itemArray.count]];
    }

    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndex:)]) {
        return [self.delegate collectionView:collectionView
                        didSelectItemAtIndex:(indexPath.row % self.itemArray.count)];
    }
}


- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGRect targetRect = CGRectMake(collectionView.contentOffset.x,
                                   0.0f,
                                   collectionView.bounds.size.width,
                                   collectionView.bounds.size.height);
    
    CGFloat width = MAX(cell.frame.size.width, 1.0f);
    
    CGRect visibleArea = CGRectIntersection(targetRect, cell.frame);
    
    CGFloat alpha = visibleArea.size.width / width;
    
    cell.alpha = alpha;
}

#pragma mark - UICollectionViewDelegate

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    if (!decelerate) {
//        // Calculate where the collection view should be at the right-hand end item
//        float itemWidth = [self.collectionViewLayout itemSize].width + self.collectionViewLayout.minimumInteritemSpacing;
//        float contentOffsetWhenFullyScrolledRight = itemWidth * (2 * self.itemArray.count * CELL_COUNT_MULTIPER / 3);
//        float contentOffsetWhenFullyScrolledLeft  = itemWidth * (self.itemArray.count * CELL_COUNT_MULTIPER / 3);
//        
//        if (scrollView.contentOffset.x + __FLT_EPSILON__ >= contentOffsetWhenFullyScrolledRight) {
//            
//            // user is scrolling to the right from the last item to the 'fake' item 1.
//            // reposition offset to show the 'real' item 1 at the left-hand end of the collection view
//            NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:(self.itemArray.count * CELL_COUNT_MULTIPER / 3) inSection:0];
//            
//            [self.collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//            
//        } else if (scrollView.contentOffset.x <= contentOffsetWhenFullyScrolledLeft + __FLT_EPSILON__)  {
//            
//            // user is scrolling to the left from the first item to the fake 'item N'.
//            // reposition offset to show the 'real' item N at the right end end of the collection view
//            
//            NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:(2 * self.itemArray.count * CELL_COUNT_MULTIPER / 3 - 1) inSection:0];
//            
//            [self.collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//            
//        }
//    }
//}
//
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    
//    // Calculate where the collection view should be at the right-hand end item
//    float itemWidth = [self.collectionViewLayout itemSize].width + self.collectionViewLayout.minimumInteritemSpacing;
//    float contentOffsetWhenFullyScrolledRight = itemWidth * (2 * self.itemArray.count * CELL_COUNT_MULTIPER / 3);
//    float contentOffsetWhenFullyScrolledLeft  = itemWidth * (self.itemArray.count * CELL_COUNT_MULTIPER / 3);
//    
//    if (scrollView.contentOffset.x + __FLT_EPSILON__ >= contentOffsetWhenFullyScrolledRight) {
//
//        // user is scrolling to the right from the last item to the 'fake' item 1.
//        // reposition offset to show the 'real' item 1 at the left-hand end of the collection view
//        NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:(self.itemArray.count * CELL_COUNT_MULTIPER / 3) inSection:0];
//        
//        [self.collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//        
//    } else if (scrollView.contentOffset.x <= contentOffsetWhenFullyScrolledLeft + __FLT_EPSILON__)  {
//        
//        // user is scrolling to the left from the first item to the fake 'item N'.
//        // reposition offset to show the 'real' item N at the right end end of the collection view
//        
//        NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:(2 * self.itemArray.count * CELL_COUNT_MULTIPER / 3 - 1) inSection:0];
//        
//        [self.collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//        
//    }
//}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray *cells = [self.collectionView visibleCells];
    
    CGRect targetRect = CGRectMake(scrollView.contentOffset.x,
                                   0.0f,
                                   self.collectionView.bounds.size.width,
                                   self.collectionView.bounds.size.height);

    for (UICollectionViewCell *cell in cells) {
        CGFloat width = MAX(cell.frame.size.width, 1.0f);
        
        CGRect visibleArea = CGRectIntersection(targetRect, cell.frame);
        
        CGFloat alpha = visibleArea.size.width / width;
        
        cell.alpha = alpha;
    }
}

@end
